package com.fy56.platform.logistics.restful.api.controller.wx;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.UserCompany;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.IUserCompanyService;
import com.fy56.platform.logistics.utils.GoogleMapHelper;
import com.fy56.platform.logistics.utils.IdWorkerTools;
import com.google.common.collect.Lists;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 企业信息RestController
 * Created by li on 2018-02-01 16:05
 */
@Api(value = "Company", description = "企业信息", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/company")
public class CompanyController {

	@Autowired
	private ICompanyInfoService iCompanyService;

	@Autowired
	private IUserCompanyService userCompanyService;

	private static Logger log = Logger.getLogger(CompanyController.class);

	@RequestMapping(value = "/findCompanyByArea", method = RequestMethod.POST)
	@ApiOperation(value = "获取企业信息")
	@Authorization
	public ResponseEntity findCompanyByArea(@RequestParam String data) {

		//data参数说明：
		// 1.行政区划编码：administrativeDivisionCode（企业所属区域的行政区划编码）
		// 2.用户手机定位的经度：longitude（用于实时计算用户与企业的距离）
		// 3.用户手机定位的纬度：latitude （用于实时计算用户与企业的距离）
		// 4.用户ID：userId （用于获取关注的企业）
		// 5.公司名称：name （用于快速查询企业）
		// 6.是否开启下单功能的标识：makeOrderFlag（用于下单时的企业选择）
		// 7.是否开启取款功能的标识：withdrawFlag（用于取款时的企业选择）
		//String userId = JSON.parseObject(data).getString("userId");

		List<Company> list = Lists.newArrayList();
		Company company = null;
		try {
			company = JSON.parseObject(data,Company.class);
			if(company == null){
				return new ResponseEntity(new ResultModel(100,"参数有误",null), HttpStatus.OK);
			}
			if(company.getUserId() != null){
				list = iCompanyService.getCompanyListByUserId(company);
			}else{
				list = iCompanyService.getCompanyListWithOutUserId(company);
			}
			//设置企业距用户的距离
			setDistance(company,list);
			return new ResponseEntity(ResultModel.ok(list), HttpStatus.OK);
		} catch (Exception e) {
			log.error("获取企业信息失败--参数：" + data,e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "获取企业信息失败"), HttpStatus.OK);
		} finally {
			list = null;
			company = null;
		}
	}

	/**
	 * 设置企业距用户的距离
	 *
	 * @param company
	 * @param list
	 */
	private void setDistance(Company company,List<Company> list){
		Double longitude = company.getLongitude();
		Double latitude = company.getLatitude();
		if(longitude != null && latitude != null){
			if(list != null && list.size() > 0){
				for(Company model : list){
					if(model.getLongitude() != null && model.getLatitude() != null){
						model.setDistance(GoogleMapHelper.getDistance(longitude,latitude,model.getLongitude(),model.getLatitude()));
					}
				}
			}
		}
	}

	@RequestMapping(value = "/followCompany", method = RequestMethod.POST)
	@ApiOperation(value = "关注企业")
	@Authorization
	public ResponseEntity followCompany(@RequestParam String userId,@RequestParam String companyId) {
		List<Company> list = null;
		List<UserCompany> userCompanys = null;
		UserCompany model = new UserCompany();
		try {
			model.setUserId(Long.valueOf(userId));
			model.setCompanyId(Long.valueOf(companyId));
			userCompanys = userCompanyService.select(model);
			//若已关注，提示：已关注
			if (userCompanys != null && userCompanys.size() > 0) {
				return new ResponseEntity(new ResultModel( "已关注该企业啦!"), HttpStatus.OK);
			}
			model.setId(Long.valueOf(IdWorkerTools.getInstance().getId()));
			model.setIsDefault(0);
			return new ResponseEntity(ResultModel.ok(userCompanyService.insert(model)), HttpStatus.OK);
		} catch (Exception e) {
			log.error("关注企业失败",e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "关注企业失败"), HttpStatus.OK);
		} finally {
			list = null;
			model = null;
			userCompanys = null;
		}
	}

	@RequestMapping(value = "/cancelFollowCompany", method = RequestMethod.POST)
	@ApiOperation(value = "取消关注企业")
	@Authorization
	public ResponseEntity cancelFollowCompany(@RequestParam String userId,@RequestParam String companyId) {
		UserCompany model = new UserCompany();
		try {
			model.setUserId(Long.valueOf(userId));
			model.setCompanyId(Long.valueOf(companyId));
			return new ResponseEntity(ResultModel.ok(userCompanyService.delete(model)), HttpStatus.OK);
		} catch (Exception e) {
			log.error("取消关注企业失败",e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "取消关注企业失败"), HttpStatus.OK);
		} finally {
			model = null;
		}
	}

	@RequestMapping(value = "/getWebList", method = RequestMethod.POST)
	@ApiOperation(value = "获取企业信息")
	@Authorization
	public ResponseEntity getWebList(@RequestParam String code, @RequestParam String longitude, @RequestParam String latitude) {
		// 1.金融代码
		// 2.用户手机定位的经度：longitude（用于实时计算用户与企业的距离）
		// 3.用户手机定位的纬度：latitude （用于实时计算用户与企业的距离）
		try {
			return new ResponseEntity(ResultModel.ok(iCompanyService.getWebList(code,longitude,latitude,null)), HttpStatus.OK);
		} catch (Exception e) {
			log.error("获取企业信息失败",e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "获取企业信息失败"), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/selectCompanyList", method = RequestMethod.POST)
	@ApiOperation(value = "获取企业信息")
	@Authorization
	public ResponseEntity selectCompanyList() {
		List<Company> list = Lists.newArrayList();
		Company company = null;
		try {
			Company entity=null;
			list = iCompanyService.selectCompanyList(entity);
			return new ResponseEntity(ResultModel.ok(list), HttpStatus.OK);
		} catch (Exception e) {
			log.error("获取全部企业信息失败" ,e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "获取全部企业信息失败"), HttpStatus.OK);
		} finally {
			list = null;
			company = null;
		}
	}


	@RequestMapping(value = "/getCompanyInfoByCode", method = RequestMethod.GET)
	@ApiOperation(value = "查询公司信息详情 金融代码")
	public ResponseEntity<ResultModel> getCompanyInfoByCode(@RequestParam String code) {
		try {
			return new ResponseEntity(ResultModel.ok(iCompanyService.getCompanyByCode(code)), HttpStatus.OK);
		} catch (Exception e) {
			log.error("查询公司信息详情失败",e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询公司信息详情失败"), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/getWebListById", method = RequestMethod.GET)
	@ApiOperation(value = "根据区域code获取网点信息")
	public ResponseEntity<ResultModel> getWebListById(
			@ApiParam(value = "金融代码", name = "code", required = true) @RequestParam String code,
			@ApiParam(value = "经度", name = "longitude", required = true) @RequestParam String longitude,
			@ApiParam(value = "纬度", name = "latitude", required = true) @RequestParam String latitude,
			@ApiParam(value = "区域code", name = "administrativeDivisionCode") @RequestParam(required = false) String administrativeDivisionCode,
			@ApiParam(value = "网点名称", name = "wdName") @RequestParam(required = false) String wdName
	) {
		try {
			ResultModel r = iCompanyService.getWebListById(code, longitude, latitude, administrativeDivisionCode, wdName);
			if(r.getCode().equals(ResultStatus.SUCCESS.getCode())){
				return new ResponseEntity(ResultModel.ok(r.getContent()), HttpStatus.OK);
			}else{
				return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "查询网点信息失败"), HttpStatus.OK);
			}

		} catch (Exception e) {
			log.error("根据区域ID获取网点信息失败",e);
			return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "根据区域ID获取网点信息失败"), HttpStatus.OK);
		}
	}

}